<template>
	<view class="container">
		<!-- Logo部分 -->
		<view class="logo">
			<image class="logo-img" src="https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/logo.png" mode="aspectFit"></image>
			<image class="logo-title" src="https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/word-02.png" mode="aspectFit"></image>
		</view>

		<!-- 登录按钮区域 -->
		<view v-if="env == 'prod'" class="login-area">
			<!-- #ifdef MP-WEIXIN -->
			<template v-if="bankSwitch">
				<button
					v-if="agree.isAgree"
					open-type="getPhoneNumber"
					@getphonenumber="handleQuickLogin.getPhoneNumber"
					class="quick-login-btn"
					:disabled="handleQuickLogin.isLoading"
					:class="{ loading: handleQuickLogin.isLoading }"
				>
					<text>一键快速登录</text>
					<view v-if="handleQuickLogin.isLoading" class="loading-icon"></view>
				</button>
				<button v-else @tap="agree.check" class="quick-login-btn">
					<text>一键快速登录</text>
				</button>
			</template>
			<view v-else @click="handleQuickLogin.phoneSubmit" class="phone-btn xjs-btn-primary-plain">手机号登录</view>
			<!-- #endif -->
			<!-- #ifdef APP -->
			<button @tap="handleQuickLogin.submit" class="quick-login-btn" :disabled="handleQuickLogin.isLoading" :class="{ loading: handleQuickLogin.isLoading }">
				<text>一键快速登录</text>
				<view v-if="handleQuickLogin.isLoading" class="loading-icon"></view>
			</button>
			<view @click="handleQuickLogin.phoneSubmit" class="phone-btn xjs-btn-primary-plain">手机号登录</view>
			<!-- #endif -->	
		</view>
		<view v-else class="login-area">
			<!-- #ifdef MP-WEIXIN -->
			<view @click="handleQuickLogin.phoneSubmit" class="phone-btn xjs-btn-primary-plain">手机号登录</view>
			<!-- #endif -->
			<!-- #ifdef APP -->
			<button @tap="handleQuickLogin.submit" class="quick-login-btn" :disabled="handleQuickLogin.isLoading" :class="{ loading: handleQuickLogin.isLoading }">
				<text>一键快速登录</text>
				<view v-if="handleQuickLogin.isLoading" class="loading-icon"></view>
			</button>
			<view @click="handleQuickLogin.phoneSubmit" class="phone-btn xjs-btn-primary-plain">手机号登录</view>
			<!-- #endif -->	
		</view>
		<!-- 用户协议区域 -->
		<view class="agreement">
			<image
				@tap="agree.toggleAgreement"
				:src="
					agree.isAgree
						? 'https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-13.png'
						: 'https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-12.png'
				"
			/>
			<text class="agreement-text">
				本人已阅读并同意
				<text @click="toUserAgree('/pages/setting/userAgreement/index')" class="link">《灰耳朵宠物陪护用户服务协议》</text>
				和
				<text @click="toUserAgree('/pages/setting/privacyAgreement/index')" class="link">《灰耳朵宠物隐私政策》</text>
			</text>
		</view>
	</view>
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app';
import { ref, reactive } from 'vue';
import { useLoginWx,useLoginApp, isRegisterUser } from '@/hooks/useLogin';
import { useConfigStore,useConfigStoreToRefs } from '@/store/useConfigStore'
import api from '@/api';
import configs from '@/config';
const { setAppConfig } = useConfigStore()
const { bankSwitch } = useConfigStoreToRefs()
onLoad((data) => {
	setAppConfig()
	env.value = configs.env
});
const env = ref('prod')
const agree = reactive({
	isAgree: false,
	toggleAgreement: () => {
		agree.isAgree = !agree.isAgree;
	},
	check: () => {
		return new Promise((resolve) => {
			if (!agree.isAgree) {
				uni.showModal({
					title: '提示',
					content: '请先阅读并同意《灰耳朵陪宠用户服务协议》和《灰耳朵陪宠隐私政策》',
					confirmText: '确定',
					showCancel: false
				});
			}
			resolve(agree.isAgree);
		});
	}
});

const handleQuickLogin = reactive({
	isLoading: false,
	//微信
	getPhoneNumber: async (e) => {
		handleQuickLogin.isLoading = true;
		if (e.detail.errMsg == 'getPhoneNumber:ok') {
			console.log(e);
			let res: any = await api({
				method: 'POST',
				url: `/mall/user/v2/getPhoneByCode`,
				data: {
					code: e.detail.code,
					encryptedData: e.detail.encryptedData,
					iv: e.detail.iv
				}
			});
			console.log(res);
			if (res.code == 0) {
				let phoneRes: any = await isRegisterUser(res.data);
				if (phoneRes.data.length == 1) {
					useLoginWx(
						{
							phone: res.data,
							userId: phoneRes.data[0].id,
							refereeId: '',
							step: 2
						},
						() => {
							handleQuickLogin.isLoading = false;
						}
					);
					return;
				}
				if (phoneRes.data.length > 1) {
					uni.navigateTo({
						url: `/pages/login/account?phone=${res.data}&onClickLogin=onClickLogin`
					});
					return;
				}
				if (phoneRes.data.length == 0) {
					uni.navigateTo({
						url: `/pages/login/refereeCode?phone=${res.data}&onClickLogin=onClickLogin&registerWay=0`
					});
					return;
				}
			} else {
				handleQuickLogin.isLoading = false;
			}
		} else {
			handleQuickLogin.isLoading = false;
		}
	},
	//app
	submit: () => {
		handleQuickLogin.isLoading = true;
		uni.getProvider({
			service: 'oauth',
			success: (res: any) => {
				console.log(res, 'res');
				if (~res.provider.indexOf('univerify')) {
					uni.preLogin({
						provider: 'univerify',
						success: () => {
							uni.login<any>({
								provider: 'univerify',
								univerifyStyle: {
									// 自定义登录框样式
									//参考`univerifyStyle 数据结构`
									backgroundColor: '#ffffff', // 授权页面背景颜色，默认值：#ffffff
									phoneNum: {
										color: '#000000' // 手机号文字颜色 默认值：#000000
									},
									slogan: {
										color: '#8a8b90' //  slogan 字体颜色 默认值：#8a8b90
									},
									authButton: {
										normalColor: '#FF6084', // 授权按钮正常状态背景颜色 默认值：#3479f5
										highlightColor: '#FF6084', // 授权按钮按下状态背景颜色 默认值：#2861c5（仅ios支持）
										disabledColor: '#FFA6BC', // 授权按钮不可点击时背景颜色 默认值：#73aaf5（仅ios支持）
										textColor: '#ffffff', // 授权按钮文字颜色 默认值：#ffffff
										title: '本机号码一键登录' // 授权按钮文案 默认值：“本机号码一键登录”
									},
									otherLoginButton: {
										visible: 'true', // 是否显示其他登录按钮，默认值：true
										normalColor: '#f8f8f8', // 其他登录按钮正常状态背景颜色 默认值：#f8f8f8
										highlightColor: '#dedede', // 其他登录按钮按下状态背景颜色 默认值：#dedede
										textColor: '#000000', // 其他登录按钮文字颜色 默认值：#000000
										title: '其他登录方式', // 其他登录方式按钮文字 默认值：“其他登录方式”
										borderWidth: '1px', // 边框宽度 默认值：1px（仅ios支持）
										borderColor: '#c5c5c5' //边框颜色 默认值： #c5c5c5（仅ios支持）
									},
									privacyTerms: {
										defaultCheckBoxState: 'false', // 条款勾选框初始状态 默认值： true
										textColor: '#8a8b90', // 文字颜色 默认值：#8a8b90
										termsColor: '#1d4788', //  协议文字颜色 默认值： #1d4788
										prefix: '我已阅读并同意', // 条款前的文案 默认值：“我已阅读并同意”
										suffix: '并使用本机号码登录', // 条款后的文案 默认值：“并使用本机号码登录”
										privacyItems: [
											// 自定义协议条款，最大支持2个，需要同时设置url和title. 否则不生效
											{
												"url": configs.yszc, // 点击跳转的协议详情页面
												"title": "隐私协议" // 协议名称
											}
										]
									}
								},
								success(res) {
									// 登录成功
									console.log('登录成功', res);
									uniCloud
										.callFunction({
											name: 'oneClickLogin', // 你的云函数名称
											data: {
												access_token: res.authResult.access_token, // 客户端一键登录接口返回的access_token
												openid: res.authResult.openid // 客户端一键登录接口返回的openid
											}
										})
										.then(async(result:any) => {
											if (result.result.content.success) {
												uni.closeAuthView()
												let phoneRes: any = await isRegisterUser(result.result.content.phoneNumber);
												if (phoneRes.data.length == 1) {
													useLoginApp({
														phone:result.result.content.phoneNumber,
														userId: phoneRes.data[0].id,
														refereeId: '',
														step: 2
													},() => {
															handleQuickLogin.isLoading = false;
														})
													return;
												}
												if (phoneRes.data.length > 1) {
													uni.navigateTo({
														url: `/pages/login/account?phone=${result.result.content.phoneNumber}&onClickLoginApp=onClickLoginApp`
													});
													return;
												}
												if (phoneRes.data.length == 0) {
													// uni.navigateTo({
													// 	url: `/pages/login/refereeCode?phone=${result.result.content.phoneNumber}&onClickLoginApp=onClickLoginApp&registerWay=0`
													// });
													
													
													uni.showModal({
														title: '提示',
														content: '手机号不存在，请前往验证码登录',
														confirmText: '取消',
														cancelText: '确定',
														success: (res) => {
															if (res.confirm) {
															} else if (res.cancel) {
																handleQuickLogin.isLoading = false;
																handleQuickLogin.phoneSubmit()
															}
														}
													});
													return;
												}
												
											}
										}).catch(err => {
											handleQuickLogin.isLoading = false;
											handleQuickLogin.phoneSubmit()
										// 处理错误
									});
								},
								fail(res:any) {
									console.log('登录失败', res);
									handleQuickLogin.isLoading = false;
									handleQuickLogin.phoneSubmit()
								}
							});
						},
						fail(res) {
							console.log('preLogin失败', res);
							handleQuickLogin.isLoading = false;
							handleQuickLogin.phoneSubmit()
						}
					});
				} else {
					handleQuickLogin.isLoading = false;
					handleQuickLogin.phoneSubmit()
				}
			}
		});
	},
	phoneSubmit: async () => {
		if(handleQuickLogin.isLoading){
			uni.showToast({
				icon:'none',
				mask:true,
				title:'一键登录加载中，请稍后重试'
			})
			return
		}
		let res = await agree.check();
		if (res) {
			uni.navigateTo({
				url: '/pages/login/verify'
			});
		}
	}
});

const toUserAgree = (url) => {
	uni.navigateTo({
		url: url
	});
};
</script>

<style lang="scss" scoped>
@import '@/styles/common/animation.scss';

.container {
	padding: 0 40rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	background-color: #fff;
	min-height: 100vh;
}

.logo {
	margin: 160rpx auto 200rpx;
	width: 100%;

	.logo-img {
		width: 200rpx;
		height: 200rpx;
		display: block;
		margin: 0 auto;
	}

	.logo-title {
		display: block;
		margin: 24rpx auto 0;
		width: 400rpx;
		height: 46rpx;
	}
}

.login-area {
	width: 100%;
	.phone-btn{
		background-color: #fff;
		color: #333;
		border: 2rpx solid #ddd;
	}
	button {
		width: 100%;
		height: 92rpx;
		line-height: 92rpx;
		border-radius: 45rpx;
		font-size: 28rpx;
		margin-bottom: 30rpx;
		position: relative;
		transition: opacity 0.3s;

		&.quick-login-btn {
			background: var(--button-bg-color);
			color: #fff;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}
}

.agreement {
	margin-top: 40rpx;
	display: flex;
	align-items: center;
	font-size: 24rpx;
	color: #666;

	image {
		width: 32rpx;
		height: 32rpx;
		flex-shrink: 0;
		margin-right: 16rpx;
	}

	.agreement-text {
		line-height: 32rpx;
	}

	.link {
		color: var(--color-primary);
	}
}
</style>
